package com.giraffe.aiochat.server.handler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Map;

import com.giraffe.aiochat.model.Message;
import com.giraffe.aiochat.model.MessageType;
import com.giraffe.aiochat.model.User;
import com.giraffe.aiochat.server.manager.ClientManager;
import com.giraffe.aiochat.utils.MessageUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MessageHandler {
    private static final Logger logger = LoggerFactory.getLogger(MessageHandler.class);
    private final ClientManager clientManager = ClientManager.getInstance();

    public MessageHandler() {
    }

    public void handleMessage(String jsonStr, AsynchronousSocketChannel clientChannel) {
        try {
            Message message = MessageUtils.fromJson(jsonStr);
            logger.debug("Received message: {}", message.getContent());
            handleJoin(message, clientChannel);
            switch (message.getType()) {
                case CHAT:
                case SYSTEM:
                    broadcast(jsonStr, clientChannel);
                    break;
            }
        } catch (Exception e) {
            logger.error("Error processing message", e);
        }
    }

    public void handleJoin(Message message, AsynchronousSocketChannel clientChannel) throws IOException {
        if (clientManager.getUser(clientChannel) == null) {
            String clientAddress = clientChannel.getRemoteAddress().toString();
            clientManager.addClient(clientChannel,new User(message.getNickname(),clientAddress));
            logger.info("New user joined: {} ：{}",clientAddress, message.getNickname());
            Message joinMsg = new Message(MessageType.SYSTEM, "系统", 
                message.getNickname() + " 加入了聊天室");
            broadcast(MessageUtils.toJson(joinMsg), clientChannel);
        }
    }

    public void handleLeave(String nickname, AsynchronousSocketChannel clientChannel) {
        Message leaveMsg = new Message(MessageType.SYSTEM, "系统", 
        nickname + " 离开了聊天室");
        broadcast(MessageUtils.toJson(leaveMsg), clientChannel);
    }

    private void broadcast(String message, AsynchronousSocketChannel sender) {
        byte[] messageBytes = message.getBytes();
        for (Map.Entry<AsynchronousSocketChannel, User> entry : clientManager.getClients().entrySet()) {
            AsynchronousSocketChannel client = entry.getKey();
            if (client != sender && client.isOpen()) {
                ByteBuffer msgBuffer = ByteBuffer.wrap(messageBytes);
                client.write(msgBuffer, null, new CompletionHandler<Integer, Void>() {
                    @Override
                    public void completed(Integer result, Void attachment) {
                        // 消息发送成功
                    }

                    @Override
                    public void failed(Throwable exc, Void attachment) {
                        logger.error("Broadcast failed", exc);
                    }
                });
            }
        }
    }
}